import { useState, useRef, useEffect } from "react";
import WaveInput from "@/components/other/Search/index";
import { searchArticle } from "@/utils/front/index";
import Comment from "@/components/other/Comment/index";
import LoginModal from "@/components/other/Login/index";
import styles from "./styles.module.less";
import { useSelector } from "react-redux";
import { setLogin } from "@/store/modules/user";
import { useDispatch } from "react-redux";

// 定义文章数据的接口
interface ArticleData {
  articleId: number;
  title: string;
  content: string;
}
// 清除橙色样式
const clearColor = () => {
  document.querySelectorAll(`.${styles.title}`).forEach((titleElement) => {
    titleElement.querySelectorAll("*").forEach((child) => {
      (child as HTMLElement).style.removeProperty("color");
    });
  });
};

function Article() {
  // 状态管理：搜索输入的值和搜索结果
  const [searchValue, setSearchValue] = useState<string>("");
  // 搜索的文章数据
  const [searchResults, setSearchResults] = useState<ArticleData[]>([]);

  // 搜索函数
  const handleSearch = (value: string) => {
    setSearchValue(value);
    searchArticle({ content: value }).then((res: any) => {
      if (res.status === 200 && res.data) {
        setSearchResults(res.data); // 更新搜索结果
      } else {
        setSearchResults([]); // 如果没有数据或出错，重置搜索结果为空
      }
    });
  };

  // 文本高亮处理
  const highlightKeyword = (text: string, keyword: string) => {
    const regex = new RegExp(keyword, "gi");
    return text.replace(
      regex,
      `<span style="color: orange;font-weight: bold;">${keyword}</span>`
    );
  };

  // 控制文章是否展示
  const [showArticle, setShowArticle] = useState(false);
  const [tableOfContents, setTableOfContents] = useState<
    {
      identify: string;
      level: number;
      text: string | null;
    }[]
  >([]);
  // 当前文章数据

  interface Article {
    articleId: string;
    content: string;
  }

  const [articles, setArticles] = useState<Article | null>(null);

  const contentRef = useRef(null);

  const bottomRef = useRef<HTMLDivElement>(null);

  // 处理富文本article逻辑
  const slide = (article: any) => {
    console.log("article", article);

    const parser = new DOMParser();
    const doc = parser.parseFromString(article.content, "text/html");

    const headings = Array.from(
      doc.body.querySelectorAll("h1, h2, h3, h4, h5, h6")
    );
    const toc = headings.map((heading, index) => {
      const id = `heading-${index}`;
      heading.setAttribute("id", id);
      return {
        identify: id,
        level: parseInt(heading.tagName.charAt(1), 10),
        text: heading.textContent,
      };
    });

    setTableOfContents(toc);

    const updatedHtml = doc.documentElement.outerHTML;
    setArticles({ articleId: article.articleId, content: updatedHtml });
    clearColor();
    setShowArticle(true);
    // 设置一个状态来触发滚动操作
    setScrollToBottom(true);
  };
  // 处理文章滚动
  const scrollToHeading = (id: string) => {
    clearColor();
    const titleEle = document.querySelector(
      `.${styles.toc_item}[data-identify="${id}"]`
    );

    console.log("titleEle", titleEle);

    if (titleEle) (titleEle as HTMLElement).style.color = "orange";

    const current = document.getElementById(id);
    current?.scrollIntoView({ behavior: "smooth" });
  };

  // 状态用于触发滚动操作
  const [scrollToBottom, setScrollToBottom] = useState(false);

  // 页面滚动
  useEffect(() => {
    if (scrollToBottom && bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: "smooth", block: "start" });
      // 滚动完成后重置状态
      setScrollToBottom(false);
    }
  }, [scrollToBottom]);
  // 渲染搜索结果的函数
  const renderSearchResults = () => {
    if (searchResults.length === 0) {
      return <div className={styles.no_results}>未找到相关结果。</div>;
    }

    return (
      <div className={styles.search_result}>
        {searchResults.map((article) => (
          <div
            key={article.articleId + "111111"}
            className={styles.item}
            onClick={() => {
              console.log(article.articleId + "111111");

              slide(article);
            }}
          >
            <div
              dangerouslySetInnerHTML={{
                __html: highlightKeyword(article.title, searchValue),
              }}
              style={{
                fontWeight: "bold",
                fontSize: "18px",
              }}
            ></div>
            <div
              dangerouslySetInnerHTML={{
                __html: getFirstSentence(article.content, searchValue),
              }}
              style={{
                height: "67%",
              }}
            ></div>
          </div>
        ))}
      </div>
    );
  };

  // 寻找并截取第一处包含关键字的句子的函数
  const getFirstSentence = (content: string, keyword: string) => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(content, "text/html");

    // 获取文档的纯文本内容
    const textContent = doc.documentElement.textContent || "";

    const sentences = textContent.split(/[.!?]/); // 将内容分割成句子
    for (const sentence of sentences) {
      if (sentence.toLowerCase().includes(keyword.toLowerCase())) {
        return highlightKeyword(sentence, keyword); // 高亮并返回匹配的句子
      }
    }

    // 如果没有找到匹配的句子，则返回内容的第一句话并进行高亮处理
    const firstSentence = textContent.split(/[.!?]/)[0];
    return highlightKeyword(firstSentence, keyword);
  };

  // 登录模块
  const [modalVisible, setModalVisible] = useState(false);

  const { login } = useSelector((state: any) => state.user);
  const disPatch = useDispatch();
  // 监听login状态的变化
  useEffect(() => {
    if (login) {
      setModalVisible(true);
    }
  }, [login]);
  const handleCancel = () => {
    setModalVisible(false);
    disPatch(setLogin(false));
    console.log("login", login);
  };
  const handleConfirm = () => {
    setModalVisible(false);
  };

  //结构的渲染
  return (
    <div className={styles.article}>
      {/* <button style={{ marginTop: "100px" }} onClick={handleLogin}>
        登录
      </button> */}
      <LoginModal
        visible={modalVisible}
        onCancel={handleCancel}
        onConfirm={handleConfirm}
      />
      <div className={styles.search}>
        <WaveInput onSearch={handleSearch} /> {/* 渲染搜索输入组件 */}
        {renderSearchResults()} {/* 渲染搜索结果 */}
      </div>
      {showArticle && (
        <div className={styles.bottom} ref={bottomRef}>
          <div className={styles.title}>
            {tableOfContents.map((item: any) => (
              <div
                key={item.identify + item.level}
                className={`${styles.toc_item} ${
                  styles[`level_${item.level}`]
                }`}
                data-identify={item.identify}
                onClick={() => {
                  scrollToHeading(item.identify);
                }}
              >
                {item.text}
              </div>
            ))}
          </div>
          <div className={styles.content}>
            <div
              style={{ lineHeight: "2.5", marginBottom: "20px" }}
              dangerouslySetInnerHTML={{ __html: articles?.content ?? "" }}
              ref={contentRef}
            />
            <Comment id={articles?.articleId ?? ""}></Comment>
          </div>
        </div>
      )}
    </div>
  );
}

export default Article;
